package com.aliware.tianchi;

import com.aliware.tianchi.common.TianchiRpcContants;
import com.aliware.tianchi.loadbalance.ProviderStatus;
import org.apache.dubbo.common.Constants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

/**
 * @author daofeng.xjf
 *
 * 客户端过滤器
 * 可选接口
 * 用户可以在客户端拦截请求和响应,捕获 rpc 调用时产生、服务端返回的已知异常。
 */
@Activate(group = Constants.CONSUMER)
public class GateWayFilter implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        ProviderStatus providerStatus =  ProviderStatus.providerStatus(invoker,invocation);
        providerStatus.beginCount();
        RpcContext.getContext().setAttachment(TianchiRpcContants.BEGIN_KEY, String.valueOf(System.currentTimeMillis()));
        return invoker.invoke(invocation);
    }

    @Override
    public Result onResponse(Result result, Invoker<?> invoker, Invocation invocation) {
        boolean isError = result.hasException();
        long begin = Long.parseLong(RpcContext.getContext().getAttachment(TianchiRpcContants.BEGIN_KEY));
        long elapsed = System.currentTimeMillis() - begin;
        ProviderStatus providerStatus =  ProviderStatus.providerStatus(invoker,invocation);
        providerStatus.endCount(elapsed, !isError);
        return result;
    }
}
